package com.mymall.basic.controller;

import cn.hutool.extra.ftp.Ftp;
import com.mymall.basic.config.FtpClientUtil;
import com.mymall.basic.entity.UploadFileEntity;
import com.mymall.basic.service.UploadFileService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

import javax.servlet.http.HttpServletResponse;
import java.io.ByteArrayOutputStream;
import java.io.File;
import java.io.IOException;
import java.io.OutputStream;

@RestController
@RequestMapping("basic/file")
public class BaseFtpShowController {

    @Autowired
    FtpClientUtil clientUtil;

    @Autowired
    private UploadFileService uploadFileService;

    @RequestMapping("/show/{fileId}")
    public void upload(@PathVariable int fileId, HttpServletResponse response) {

        UploadFileEntity fileEntity = uploadFileService.getById(fileId);

        String ftpPath = fileEntity.getPath();

        Ftp ftp = clientUtil.getFtp();

        ByteArrayOutputStream out = new ByteArrayOutputStream();

        ftp.download(ftpPath, fileEntity.getName(), out);

        response.setCharacterEncoding("utf-8");
        response.setContentType("multipart/form-data");
        response.setHeader("Content-Disposition", "attachement;fileName=" + fileEntity.getName());

        try {
            OutputStream responseOut = response.getOutputStream();
            responseOut.write(out.toByteArray());
            responseOut.close();
        } catch (IOException e) {
            e.printStackTrace();
        }

    }

    @RequestMapping("/detail/{fileId}")
    public UploadFileEntity queryById(@PathVariable int fileId){
        return uploadFileService.getById(fileId);
    }


    public static void main(String[] args) {

        Ftp ftp = new Ftp("192.168.33.10", 21, "davion", "davion");
//
//        ftp.upload("/upload/"+DateUtil.today()+"/",new File("C:\\Users\\Administrator\\Pictures\\01.jpg"));
//        ftp.close();


        ftp.download("/null2021/09/12/024117bf691241d0948f20fa409a5bab_01.jpg", new File("C:\\Users\\Administrator\\Pictures\\111111.jpg"));


    }


}
